import { dom } from "../tool";
import Slide from "./Slide";


interface PropType {
    value?: string | number | null;
    onChange?: (value: string | number | null | undefined) => void;
    label?: string | HTMLElement;
    min?: number;
    max?: number;
    target?: HTMLElement;
}

interface SizeSetType {
    new (props?: PropType): SizeSetType;
    value: string | number | undefined | null;
    setValue: (value?: string | number | null) => void;
    render: (node?: HTMLElement) => HTMLElement;
    onChange?: (value: string | number | null | undefined) => void;
}

function SizeSet(this: SizeSetType, props: PropType) {
    const { value, onChange, label, min = 0, max = 100, target } = props || {};
    this.onChange = onChange;
    const input: any = dom('input', { className: 'gkh-input', style: 'width: 64px' });
    const arrow = dom('div', { className: 'gkh-arrow-down', style: 'position:absolute; top: 6px; right: 8px;' });
    const slide = new Slide({
        hidden: true,
        onChange: (value) => {
            this.value = value ? Math.ceil(value) : value;
            if (this.onChange) this.onChange(this.value);
            input.value = this.value;
        },
        min,
        max,
        style: "z-index:10; background-color:#ffffff; box-shadow:0 0 2px #808080;"
    });
    const slideDiv = dom('div', { child: slide.render(), style: 'position:absolute; width: 100%; height: 20px;' });
    const childs = [];
    if (label) {
        if (label instanceof Node) {
            childs.push(dom('label', { child: label }));
        } else {
            childs.push(dom('label', { innerText: label }));
        }
    }
    childs.push(dom('div', { childs: [input, arrow], style: 'display: inline-block;position: relative;' }));
    childs.push(slideDiv);
    const container = dom('div', {
        className: 'gkh-form-item',
        childs,
        target
    });
    arrow.onclick = (event: any) => {
        if (event.stopPropagation) {
            event.stopPropagation();
        }
        else {
            event.cancelBubble = true;
        }
        slide.setHidden(!slide.hidden);
    }
    this.setValue = (arg) => {
        if (arg == null || arg == undefined) {
            this.value = null;
            input.value = "";
        } else if (arg >= min && arg <= max) {
            this.value = arg;
            input.value = arg;
        }
        slide.setValue('string' == typeof arg ? parseInt(arg) : arg);
    }
    input.onchange = () => {
        const arg = parseInt(input.value);
        if (arg >= min && arg <= max) {
            this.value = arg;
            slide.setValue(arg);
            if (this.onChange) this.onChange(this.value);
        }else{
            input.value = this.value;
        }
    }
    this.setValue(value);
    this.render = (node) => {
        if (node) node.appendChild(container);
        this.setValue(value);
        return container;
    }
    return this;
}

export default SizeSet as unknown as SizeSetType;
